package com.company.ems.controller;


import com.company.ems.dao.EmployeeDAO;
import com.company.ems.dao.EmployeeDAOImpl;
import com.company.ems.model.Employee;
import com.company.ems.model.User;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.time.LocalDate;
import java.util.List;

@WebServlet("/employee/*")
public class EmployeeServlet extends HttpServlet {
    private EmployeeDAO employeeDAO = new EmployeeDAOImpl();

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        String action = request.getPathInfo(); // /list, /add, /edit, /delete, /view
        HttpSession session = request.getSession();

        String contextPath = request.getContextPath();


        User currentUser = (User) session.getAttribute("user");

        switch (action) {
            case "/list":
//                List<Employee> employees = employeeDAO.getAllEmployees();
//                request.setAttribute("employees", employees);
//                request.getRequestDispatcher("/emp/list.jsp").forward(request, response);
//                break;

                // 安全解析日期参数
                LocalDate hireDateFrom = null;
                LocalDate hireDateTo = null;

                // 安全获取 page 参数
                int page = 1;
                String pageStr = request.getParameter("page");
                if (pageStr != null && !pageStr.trim().isEmpty()) {
                    try {
                        page = Integer.parseInt(pageStr);
                        if (page < 1) page = 1; // 最小为第1页
                    } catch (NumberFormatException e) {
                        page = 1; // 非法值默认第1页
                    }
                }

                int recordsPerPage = 10;

                // 安全获取查询条件
                String name = request.getParameter("name");
                String department = request.getParameter("department");
                String position = request.getParameter("position");
                String hireDateFromStr = request.getParameter("hireDateFrom");
                String hireDateToStr = request.getParameter("hireDateTo");

// 工具方法：判断是否为有效非空字符串
                if (hireDateFromStr != null && !hireDateFromStr.trim().isEmpty()) {
                    try {
                        hireDateFrom = LocalDate.parse(hireDateFromStr.trim());
                    } catch (Exception e) {
                        // 忽略无效日期，可选：记录日志或设为 null
                        hireDateFrom = null;
                    }
                }
                if (hireDateToStr != null && !hireDateToStr.trim().isEmpty()) {
                    try {
                        hireDateTo = LocalDate.parse(hireDateToStr.trim());
                    } catch (Exception e) {
                        hireDateTo = null;
                    }
                }

                // 调用 DAO
                List<Employee> employees = employeeDAO.searchEmployeesWithPagination(
                        name, department, position, hireDateFrom, hireDateTo, page, recordsPerPage
                );
                int totalRecords = employeeDAO.countSearchResults(
                        name, department, position, hireDateFrom, hireDateTo
                );
                int totalPages = totalRecords > 0 ? (int) Math.ceil((double) totalRecords / recordsPerPage) : 1;

                // 设置属性
                request.setAttribute("employees", employees);
                request.setAttribute("currentPage", page);
                request.setAttribute("totalPages", totalPages);

                request.getRequestDispatcher("/emp/list.jsp").forward(request, response);
                break;

            case "/add":
                request.getRequestDispatcher("/emp/add.jsp").forward(request, response);
                break;

            case "/edit":
                int editId = Integer.parseInt(request.getParameter("id"));
                Employee empToEdit = employeeDAO.getEmployeeById(editId);
                if (empToEdit != null) {
                    request.setAttribute("employee", empToEdit);
                    request.getRequestDispatcher("/emp/edit.jsp").forward(request, response);
                } else {
                    response.sendRedirect("employee/list");
                }
                break;

            case "/delete":
                int deleteId = Integer.parseInt(request.getParameter("id"));
                employeeDAO.deleteEmployee(deleteId);
                response.sendRedirect("list");
                break;

            case "/view":
                int viewId = Integer.parseInt(request.getParameter("id"));
                Employee empToView = employeeDAO.getEmployeeById(viewId);
                if (empToView != null) {
                    request.setAttribute("employee", empToView);
                    request.getRequestDispatcher("/emp/view.jsp").forward(request, response);
                } else {
                    response.sendRedirect("list");
                }
                break;

            default:
                response.sendRedirect(contextPath+"/error/404.jsp");
                break;
        }
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        String action = request.getPathInfo();
        HttpSession session = request.getSession();
        User currentUser = (User) session.getAttribute("user");

        request.setCharacterEncoding("UTF-8");

        if ("/add".equals(action)) {
            Employee newEmp = new Employee();
            newEmp.setName(request.getParameter("name"));
            newEmp.setDepartment(request.getParameter("department"));
            newEmp.setPosition(request.getParameter("position"));
            newEmp.setSalary(Double.parseDouble(request.getParameter("salary")));
            newEmp.setEmail(request.getParameter("email"));
            newEmp.setPhone(request.getParameter("phone"));
            newEmp.setHireDate(LocalDate.parse(request.getParameter("hireDate")));
            newEmp.setCreatedBy(currentUser);

            employeeDAO.addEmployee(newEmp);
            response.sendRedirect("list");

        } else if ("/edit".equals(action)) {
            int id = Integer.parseInt(request.getParameter("id"));
            Employee emp = employeeDAO.getEmployeeById(id);

            emp.setName(request.getParameter("name"));
            emp.setDepartment(request.getParameter("department"));
            emp.setPosition(request.getParameter("position"));
            emp.setSalary(Double.parseDouble(request.getParameter("salary")));
            emp.setEmail(request.getParameter("email"));
            emp.setPhone(request.getParameter("phone"));
            emp.setHireDate(LocalDate.parse(request.getParameter("hireDate")));

            employeeDAO.updateEmployee(emp);
            response.sendRedirect("list");
        }
    }
}